package cn.yu_lu.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.UndeclaredThrowableException;

public class FileUtil {

	/**
	 * 判断指定路径的文件是否存在
	 * @param filePath 文件路径
	 * @return 如果文件存在返回true,否则返回false.当传入的路径为空时返回null
	 */
	public static boolean isExists(String filePath){
		if(JudgeUtil.isBlank(filePath)) return false;
		return (new File(filePath)).exists();
	}
	
	/**
	 * 获取文件的文本内容
	 * @param filePath 文件路径
	 * @return 文件内容的字符串表示，当传入空的文件路径时返回null
	 * @throws IllegalArgumentException 当指定的文件不存在时或不是文件时抛出
	 * 		   UncheckedIOException 当读取文件内容失败时抛出
	 * 		   UndeclaredThrowableException 当关闭文件读取流失败时抛出
	 */
	public static String getText(String filePath){
		if(JudgeUtil.isBlank(filePath)) return null;
		File file=new File(filePath);
		if(!file.exists()||!file.isFile()){
			throw new IllegalArgumentException();
		}else{
			BufferedReader reader=null;
			try {
				StringBuilder builder=new StringBuilder();
				reader=new BufferedReader(new FileReader(file));
				String temp=null;
				while((temp=reader.readLine())!=null){
					builder.append(temp);
				}
				return builder.toString();
			} catch (FileNotFoundException e) {
				throw new IllegalArgumentException();
			} catch (IOException e) {
				throw new UncheckedIOException(e);
			}finally{
				try {
					if(reader!=null) reader.close();
				} catch (IOException e) {
					throw new UndeclaredThrowableException(e); 
				}
			}
		}
	}
	
	/**
	 * 将字符串内容写入指定文件
	 * @param filePath 文件路径
	 * @param text 写入内容
	 * @return true:写入成功
	 * @throws IllegalArgumentException 文件路径为空时抛出,
	 * 		   UnsupportedOperationException 文件创建失败时抛出
	 * 		   UncheckedIOException 文件写入失败时抛出
	 */
	public static boolean writeText(String filePath,String text){
		if(JudgeUtil.isBlank(filePath)) throw new IllegalArgumentException();
		if(JudgeUtil.isBlank(text)) return true;
		File file=new File(filePath);
		if(!file.exists()){
			if(!file.mkdirs()) throw new UnsupportedOperationException();
		}
		BufferedWriter writer=null;
		try {
			writer=new BufferedWriter(new FileWriter(file));
			writer.write(text);
			return true;
		} catch (IOException e) {
			throw new UncheckedIOException(e);
		}finally{
			try {
				if(writer!=null) writer.close();
			} catch (IOException e) {
				throw new UndeclaredThrowableException(e);
			}
		}
	}
}
